import { login, sysProfile, sysUser } from '@/api/user.js'
import { getToken, setToken } from '@/utils/auth'
import asyncRoutes from '@/router/modules/index.js'
import router from '@/router'
import { constantRoutes } from '@/router'
import { resetRouter } from '@/router'
const state = {
  token: getToken() || '',
  userInfo: ''
}
const mutations = {
  setToken (state, value) {
    state.token = value
    setToken(value)
  },
  setUserInfo (state, value) {
    state.userInfo = value
  },
  // 退出登陆处理
  logout (state) {
    state.token = ''
    setToken('')
    state.userInfo = ''
    // 重置路由
    resetRouter()
  }
}
const actions = {
  // 登陆调用
  async toLogin ({ commit }, value) {
    const res = await login(value)
    commit('setToken', res.data)
    // console.log(res)
  },
  // 获取用户个人信息(不包括头像)
  async getUserInfo ({ commit, state }) {
    // 获取员工信息,不包括头像
    const res = await sysProfile()
    // commit('setUserInfo', res.data)
    // 通过userId过去其他信息
    const res2 = await sysUser(res.data.userId)
    // 把信息合并
    commit('setUserInfo', { ...res.data, ...res2.data })
    // console.log('用户个人信息', res, res2)
    const newArr = asyncRoutes.filter(item => {
      return state.userInfo.roles.menus.includes(item.name)
    })
    newArr.push({ path: '*', redirect: '/404', hidden: true })
    commit('routes/setRoutesList', [...constantRoutes, ...newArr], {
      root: true
    })
    router.addRoutes(newArr)
  }
}
const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
